﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SystemCenter.Orchestrator.Integration;
using SocialMediaIntegrationPack.Properties;
using RestSharp;
using RestSharp.Authenticators;


namespace SocialMediaIntegrationPack
{
    /// <summary>
    /// Base class for all Yammer activities
    /// </summary>
    public class YammerActivity
    {

        private static readonly string consumerKey = "7bwtr5rzi7nLQGLkA35aA";
        private static readonly string consumerSecret = "V9yIOwKqjQfOKn1dznvL8yFZ14RmYhw5OwF7YVrVQ";

        public static RestClient GetClient(string oauth_token, string oauth_token_secret)
        {
            var client = new RestClient("https://www.yammer.com")
            {
                Authenticator = OAuth1Authenticator.ForProtectedResource(
                    consumerKey, consumerSecret, oauth_token, oauth_token_secret
                    )
            };

            return client;
        }

        /// <summary>
        /// Secutiry configuration for OAuth
        /// </summary>
        [ActivityConfiguration]
        public OAuthConfiguration Configuration { get; set; }

        /// <summary>
        /// Additional input parameter
        /// </summary>
        [ActivityInput("ID")]
        public string Id { get; set; }

        /// <summary>
        /// Text of response
        /// </summary>
        [ActivityOutput("Yammer Response")]
        public string Response { get; set; }

        /// <summary>
        /// Output structure which contains all downloaded or sent messages
        /// </summary>
        [ActivityOutput]
        public List<YammerMessage> Messages { get; set; }

        protected void CheckId()
        {
            long i;
            if (String.IsNullOrEmpty(Id) || !Int64.TryParse(Id, out i) || i <= 0)
            {
                throw new ArgumentException(Resources.INCORRECT_ID);
            }
        }

        protected static void CheckResponse(RestResponse<YammerMessages> r)
        {
            if (r.ErrorException != null)
            {
                throw r.ErrorException;
            }
            if (r.StatusCode == System.Net.HttpStatusCode.BadRequest || r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                throw new Exception(r.StatusDescription);
            }
        }
    }
}
